<template>
<div style="width: 100%;height: 100vh;background-color: darkcyan;overflow: hidden">
  <div style="width: 400px ; margin: 150px auto">
    <div style="color: #cccccc; font-size: 24px;text-align: center;padding: 30px">欢迎光临</div>
    <el-form ref="form" :model="form" label-width="120px" :rules="rules">
      <el-form-item label="用户名：" prop="username">
        <el-input prefix-icon="el-icon-user-solid" v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input  v-model="form.password" show-password></el-input>
<!--        prefix-icon="el-icon-lock"-->
      </el-form-item>
      <el-form-item>
        <el-button style="width: 50%" @click="login">登录</el-button>
      </el-form-item>
      <el-form-item>
        <el-button style="width: 50%" @click="regist">注册</el-button>
      </el-form-item>
    </el-form>
    </div>
</div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "Login",
  data()
  {
    return{
      form:{},
    rules: {
      username: [
        {
          required: true,
          message: '请输入用户名',
          trigger: 'blur',
        },
      ],
          password: [
        {
          required: true,
          message: '请输入密码',
          trigger: 'blur',
        },
      ],
    }
    }
  },
  created() {
    sessionStorage.removeItem("user")
  },
  methods: {
    regist(){
      this.$router.push("/register")      //跳转到注册页面
    },
    login(){
      this.$refs['form'].validate((valid) => {      //验证登录合法才会发送请求
        if (valid) {
          request.post("/user/login",this.form).then(res =>{
            if (res.code === '0') {
              this.$message(
                  {
                    type:"success",
                    message:"登录成功"
                  }
              )
              sessionStorage.setItem("user", JSON.stringify(res.data))  // 缓存用户信息
              // request.get("/user/" + this.user.id).then(res => {
              //   if (res.code === '0') {
              //     this.user = res.data
              //   }
              // })
              this.$router.push("/")      //跳转到主页

            } else {
              this.$message(
                  {
                    type:"error",
                    message:res.msg
                  }
              )
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>